package com.firewolf.hibernate.relationship.many_many_both.main;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.relationship.many_many_both.dto.Category;
import com.firewolf.hibernate.relationship.many_many_both.dto.Item;


public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;
	
	@Test
	public void saveCustomer(){
		openSession();
		
		Item item1 = new Item();
		item1.setItemName("Item1");
		
		Item item2 = new Item();
		item1.setItemName("Item2");
		
		Category category = new Category();
		category.setCategoryName("Category1");

		Category category2 = new Category();
		category2.setCategoryName("Category2");
		
		category.getItems().add(item1);
		category.getItems().add(item2);
		
		category2.getItems().add(item1);
		category2.getItems().add(item2);
		
		item1.getCategories().add(category);
		item1.getCategories().add(category2);
		
		item2.getCategories().add(category);
		item2.getCategories().add(category2);
		
		session.save(item1);
		session.save(item2);
		session.save(category);
		session.save(category2);
		
		closeSession();
	}
	
	@Test
	public void qry(){
		openSession();
		Query createQuery = session.createQuery("from Category");
		List list = createQuery.list();
		System.out.println(list);
		closeSession();
	}
	
	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("many2many_both.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
